

from xrule.rule import Rule, RuleRepository, VersionConflictError,RepositoryManager

from typing import Callable, TypeAlias
Rules: TypeAlias = list[Rule]


class RuleEngine:

    def __init__(self, repo: RuleRepository):
        self.repo = repo

    def pattern_matcher(self, fact) -> Rules:
        """匹配规则"""
        results: Rules = []
        cache = {}

        for rule in self.repo.rules.values():
            for validator in rule.validators:
                if validator not in cache:
                    cache[validator] = validator(fact)
                if not cache[validator]:
                    break
            else:
                results.append(rule)
        return results

    def execution_engine(self, fact, retry: int = 3):
        """执行引擎"""
        while retry > 0:
            retry -= 1
            try:
                with RepositoryManager(self.repo):
                    for rule in self.pattern_matcher(fact):
                        for handler in rule.handlers:
                            handler(fact)
            except VersionConflictError:
                continue
            except Exception as e:
                print(f"Error: {e}")
                raise
                break